﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;

namespace Canteen.Core.Common
{
    public static class AntiforgerySetup
    {
        public static void AddAntiforgerySetup(this IServiceCollection services, IConfiguration configuration)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddAntiforgery(setupAction =>
            {
                var options = configuration.GetSection(AntiforgeryOptions.Configure).Get<AntiforgeryOptions>();
                var cook = setupAction.Cookie;
                cook.Name = options.CookieName;
                if (!string.IsNullOrWhiteSpace(options.CookieDomain))
                {
                    cook.Domain = options.CookieDomain;
                }
                setupAction.SuppressXFrameOptionsHeader = true;
                setupAction.HeaderName = options.HeaderName;
                setupAction.Cookie = cook;
            });
            //services.TryAddSingleton<GenerateAntiforgeryResultFilter>();
            services.TryAddSingleton<ValidateAntiforgeryAuthorizationFilter>();
            //添加Antiforgery配置选项
            //services.Configure<AntiforgeryOptions>(config);
        }
    }
}